package main

import (
	"dbGenerate/dbRead"
	"dbGenerate/fileGenerate"
	"flag"
	"fmt"
	"strings"
)

var (
	host     = flag.String("host", "", "db to connect or path")
	username = flag.String("user", "", "username to auth")
	password = flag.String("password", "", "password to gen")
	prefix   = flag.String("prefix", "db_op", "prefix of file and function generated")
	db       = flag.String("db", "", "database to read")
	table    = flag.String("table", "", "table to read")
	dbType   = flag.String("dbType", "", "which db type to read (sqlite)")
	genLang  = flag.String("genLang", "c", "generate language(c)")
	genPos   = flag.String("genPos", ".", "where to save generated file")
)

func typeTransferC(key string) string {
	switch strings.ToLower(key) {
	case "integer":
		return "int"
	case "float":
		return "float"
	case "text":
		return "char *"
	}
	return ""
}

func keyTypeTransfer(info *dbRead.DBTableInfo) {
	info_back := *info
	for k, v := range info_back.KeyMap {
		if *genLang == "c" && *dbType == "sqlite" {
			info.KeyMap[k] = typeTransferC(v)
		}
	}
}

func doTransfer() {
	var dbHandler dbRead.DBReadInterface
	var genHandler fileGenerate.FileGenInterface
	if *dbType == "sqlite" {
		dbHandler = new(dbRead.DBReadSqlite)
	}
	if *genLang == "c" {
		genHandler = new(fileGenerate.FileGenC)
	}
	fmt.Println("go to connect to ", *dbType, " of lang ", *genLang, " with db ", *host)
	err := dbHandler.Connect(*host, *username, *password)
	if err != nil {
		fmt.Println("connect fail ", err)
		return
	}
	info, err := dbHandler.Read(*db, *table)
	if err != nil {
		fmt.Println("read fail", err)
		return
	}
	keyTypeTransfer(&info)
	property := fileGenerate.FileGenProperty{
		OutPos:  *genPos,
		Prefix:  *prefix,
		Table:   *table,
		SqlType: *dbType,
	}
	err = genHandler.GenerateHeader(info, property)
	if err != nil {
		fmt.Println("generate header fail ", err)
	}
	err = genHandler.GenerateImpl(info, property)
	if err != nil {
		fmt.Println("generate impl fail ", err)
	}
}

func main() {
	flag.Parse()
	doTransfer()
}
